<template>
	<PageWrapper contentFullHeight fixedHeight :contentClass="'flex'">
		<BasicTable @register="registerTable" :keyWordInfo="keyWordInfo">
			<template #beforeTable>
				<div class="pt-3 pb-3">
					<a-button class="mr-5" type="primary" @click="handleCreate">新增</a-button>
				</div>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.key == 'action'">
					<TableAction :divider="true" :actions="createActions(record)"></TableAction>
				</template>
			</template>
		</BasicTable>
		<AddOrEditModal @register="registerModal" @success="handleSuccess"></AddOrEditModal>
	</PageWrapper>
</template>

<script setup lang="ts">
import { reactive, h } from 'vue';
import { PageWrapper, BasicTable, TableAction } from '#/components';
import { useModal, useTable } from '#/hooks';
import { deleteDept, getDeptTree } from '@/api/sys/dept';
import type { ActionItem } from '#/types';
import AddOrEditModal from './components/AddOrEditItem.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { Tag } from 'ant-design-vue';

const columns = [
	{
		title: '部门名称',
		dataIndex: 'deptName',
	},
	{
		title: '状态',
		dataIndex: 'status',
		width: 120,
		customRender: ({ record }) => {
			const status = record.status;
			const enable = status === true;
			const color = enable ? 'green' : 'red';
			const text = enable ? '启用' : '停用';
			return h(Tag, { color: color }, () => text);
		},
	},
	{
		title: '备注',
		dataIndex: 'remark',
	},
];

const keyWordInfo = reactive<Recordable>({});

const [registerTable, { reload }] = useTable({
	columns,
	rowKey: 'deptName',
	api: getDeptTree,
	actionColumn: {
		title: '操作',
		key: 'action',
		dataIndex: 'action',
		width: 240,
	},
});

const [registerModal, { openModal }] = useModal();

const { createMessage } = useMessage();

function createActions(record: Recordable): ActionItem[] {
	return [
		{
			title: '编辑',
			onClick: handleEdit.bind(null, record),
			disabled: record.username == 'admin',
		},
		{
			title: '删除',
			ifShow: record.username !== 'admin',
			popConfirm: {
				title: '是否确认删除',
				confirm: handleDelete.bind(null, record),
			},
		},
	];
}

function handleCreate() {
	openModal(true, {
		isUpdate: false,
	});
}
function handleEdit(record: Recordable) {
	openModal(true, {
		record,
		isUpdate: true,
	});
}

function handleDelete(record: Recordable) {
	deleteDept(record.deptId).then(
		() => {
			createMessage.success('删除成功');
			reload();
		},
		_err => {},
	);
}

function handleSuccess() {
	createMessage.success('操作成功');
	reload();
}
</script>
<style lang="less" scoped>
.tree {
	width: 300px;
	border-right: 1px solid #ddd;
	line-height: 45px;
	margin: 0 30px 0 0;
	.tree-wrap {
		width: 290px;
		overflow: auto;
	}
}
</style>
